package com.lh.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lh.entity.table.*;
import com.lh.mapper.*;
import com.lh.service.DsmsUserService;
import com.lh.service.ResponsiblePersonService;
import com.lh.utils.SmsGetSenderWithConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class TimeTask {

    @Resource
    private DeadlineNodeMapper deadlineNodeMapper;
    @Autowired
    private SmsGetSenderWithConfigUtil smsUtil;

    @Autowired
    private DsmsUserService dsmsUserService;
    @Resource
    private ReminderInfoMapper reminderInfoMapper;

    @Resource
    private DepartmentInfoMapper departmentInfoMapper;

    @Resource
    private RectificationInfoMapper rectificationInfoMapper;
    @Autowired
    private CompanyDataMapper companyDataMapper;
    @Resource
    private ReminderPersonMapper reminderPersonMapper;

    // 单位主要领导
    @Resource
    private DepartmentPersonMapper departmentPersonMapper;

    @Autowired
    private EnterpriseDataMapper enterpriseDataMapper;

    @Resource
    private ResponsiblePersonService responsiblePersonService;

    @Resource
    private DeadlineRectificationPeriodMapper deadlineRectificationPeriodMapper;

    @PostConstruct
    public void init() {
    }

    // 区划列表
    private static final List<String> DISTRICTS = Arrays.asList(
            "黄州区", "团风县", "红安县", "麻城市",
            "罗田县", "英山县", "浠水县", "蕲春县",
            "武穴市", "黄梅县", "龙感湖管理区", "白莲河示范区", "黄冈高新区", "市临空经济区"
    );

    private void checkCompanyWarn() {
        List<CompanyData> companyDataList = companyDataMapper.selectList(new LambdaQueryWrapper<>());
        companyDataList.forEach(item->{
            if (item.getLampStatus().equals("2")){
                String title = "红灯报警";
                String remindInfo = "您服务的企业"+item.getName()+"重点工作有红灯报警，请及时跟踪处理。";
                String personResponsible = item.getPersonResponsible();
                if (StrUtil.isNotBlank(personResponsible)) {
                    String[] nodeResponsiblePeople = personResponsible.split("[,/.、]");
                    for (String person : nodeResponsiblePeople) {
                        remindDepartment(person,25,remindInfo,item.getId());
                    }
                    String remindInfo2 = "您单位服务的企业"+item.getName()+"重点工作有红灯报警，请及时跟踪处理。";
                    remindOpertioner(item.getDepartmentName(),25,remindInfo2,item.getId());
                }
            }else if (item.getLampStatus().equals("3")){
                String title = "黄灯预警";
                String remindInfo = "您服务的企业"+item.getName()+"重点工作有黄灯预警，请及时跟踪处理。";
                String personResponsible = item.getPersonResponsible();
                if (StrUtil.isNotBlank(personResponsible)) {
                    String[] nodeResponsiblePeople = personResponsible.split("[,/.、]");
                    for (String person : nodeResponsiblePeople) {
                        remindDepartment(person,26,remindInfo,item.getId());
                    }
                    String remindInfo2 = "您单位服务的企业"+item.getName()+"重点工作有黄灯预警，请及时跟踪处理。";
                    remindOpertioner(item.getDepartmentName(),26,remindInfo2,item.getId());
                }
            }
        });
    }

    // 还没做完
    private void checkEnterpriseWarn(){
        List<EnterpriseData> companyDataList = enterpriseDataMapper.selectList(new LambdaQueryWrapper<>());
        companyDataList.forEach(item->{
            if (item.getLampStatus().equals("2")){
                String remindInfo = "您服务的企业"+item.getDepartmentName()+"重点工作有红灯报警，请及时跟踪处理。";
                String personResponsible = item.getPersonResponsible();
                if (StrUtil.isNotBlank(personResponsible)) {
                    String[] nodeResponsiblePeople = personResponsible.split("[,/.、]");
                    for (String person : nodeResponsiblePeople) {
                        remindDepartment(person,25,remindInfo,item.getId());
                    }
                }
            }else if (item.getLampStatus().equals("3")){
                String remindInfo = "您服务的企业"+item.getDepartmentName()+"重点工作有黄灯预警，请及时跟踪处理。";
                String personResponsible = item.getPersonResponsible();
                if (StrUtil.isNotBlank(personResponsible)) {
                    String[] nodeResponsiblePeople = personResponsible.split("[,/.、]");
                    for (String person : nodeResponsiblePeople) {
                        remindDepartment(person,26,remindInfo,item.getId());
                    }
                }
            }
        });

    }

    /**
     * 定时任务：更新预警级别
     * 每10分钟执行一次
     */
//    @Scheduled(cron = "0 0 8 * * ?")
//    public void updateWarnLevel() {
//        log.info("开始执行预警级别更新任务");
//        DateTime date = DateUtil.date();
//        LambdaQueryWrapper<RectificationInfo> rectificationInfoQueryWrapper = new LambdaQueryWrapper<>();
//        rectificationInfoQueryWrapper.ne(RectificationInfo::getState, "已关闭");
//        List<RectificationInfo> rectificationInfoList = rectificationInfoMapper.selectList(rectificationInfoQueryWrapper);
//        if (CollectionUtil.isEmpty(rectificationInfoList)) {
//            log.info("未找到需要处理的整改信息");
//            return;
//        }



    @Scheduled(cron = "0 30 8 * * ?")
    public void updateWarnLevel() {
        log.info("开始执行预警级别更新任务");
        DateTime date = DateUtil.date();
        LambdaQueryWrapper<RectificationInfo> rectificationInfoQueryWrapper = new LambdaQueryWrapper<>();
        rectificationInfoQueryWrapper.ne(RectificationInfo::getState, "已关闭").ne(RectificationInfo::getState, "已销号")
                .ne(RectificationInfo::getState, "已退出");
        List<RectificationInfo> rectificationInfoList = rectificationInfoMapper.selectList(rectificationInfoQueryWrapper);
        if (CollectionUtil.isEmpty(rectificationInfoList)) {
            log.info("未找到需要处理的整改信息");
            return;
        }
        // 获取所有延期调整记录
        List<DeadlineRectificationPeriod> deadlineRectificationPeriods = deadlineRectificationPeriodMapper.selectList(
                new LambdaQueryWrapper<DeadlineRectificationPeriod>()
                        .eq(DeadlineRectificationPeriod::getIsApproval, 1)
        );
        Map<Integer, List<DeadlineRectificationPeriod>> deadlineRectificationPeriodMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(deadlineRectificationPeriods)) {
            deadlineRectificationPeriodMap = deadlineRectificationPeriods.stream()
                    .filter(o -> o.getDeadlineNodeId() != null)
                    .collect(Collectors.groupingBy(DeadlineRectificationPeriod::getDeadlineNodeId));
        }

        for (RectificationInfo rectificationInfo : rectificationInfoList) {
            LambdaQueryWrapper<DeadlineNode> deadlineNodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            deadlineNodeLambdaQueryWrapper.eq(DeadlineNode::getRectificationId, rectificationInfo.getId());
            List<DeadlineNode> deadlineNodeList = deadlineNodeMapper.selectList(deadlineNodeLambdaQueryWrapper);
            if (CollectionUtil.isEmpty(deadlineNodeList)) {
                continue;
            }
            // 过滤节点
            deadlineNodeList = filiterNode(rectificationInfo, deadlineNodeList);

            for (DeadlineNode node : deadlineNodeList) {
                // 如果节点已完成，跳过处理
                if (node.getEndTime() != null) {
                    log.info("节点 {} 已完成，跳过处理", node.getId());
                    continue;
                }
                if (node.getProgress()!=null && node.getProgress().equals("/")){
                    continue;
                }
                // 获取最新的延期调整时间
                Date deadline = node.getDeadline();
                List<DeadlineRectificationPeriod> periodList = new ArrayList<>();
                if (deadlineRectificationPeriodMap.containsKey(node.getId())) {
                    periodList = deadlineRectificationPeriodMap.get(node.getId());
                    Optional<DeadlineRectificationPeriod> latestPeriod = periodList.stream()
                            .filter(p -> p.getRectificationTime() != null)
                            .max(Comparator.comparing(DeadlineRectificationPeriod::getRectificationTime));

                    if (latestPeriod.isPresent()) {
                        deadline = latestPeriod.get().getRectificationTime();
                        log.info("节点 {} 使用调整后的期限: {}", node.getId(), deadline);
                    }
                }
                if (deadline == null) {
                    log.info("节点 {} 没有设置期限，跳过处理", node.getId());
                    continue;
                }
                // 设置预警级别
                String newWarnLevel = null;
                Integer reminderType = null;
                String reminderContent = null;

                // 正确计算两个日期之间的小时差（截止时间 - 当前时间）
                long deadlineTime = deadline.getTime(); // 截止时间的毫秒数
                //
                long currentTime = new Date().getTime();    // 当前时间的毫秒数
                long diffInMillies = deadlineTime - currentTime; // 时间差（毫秒）
                long hoursBetween = diffInMillies / (1000 * 60 * 60); // 转换为小时
                // 计算时间差（小时）
                log.info("节点 {} 当前时间: {}, 期限: {}, 时间差: {} 小时",
                        node.getId(), date, deadline, hoursBetween);
                if (hoursBetween < 0) {
                    // 已超期 - 红灯（截止时间在当前时间之前）
                    newWarnLevel = "2";
                    if (periodList.isEmpty()){
                        reminderType = 24;
                        reminderContent = "重点工作" + rectificationInfo.getTitle() + "出现红灯报警，请及时关注调度。";
                        log.info("节点 {} 已超期，应设置为红灯", node.getId());
                    }else if (periodList.size() == 1){
                        reminderType = 85;
                        reminderContent = "重点工作" + rectificationInfo.getTitle() + "出现二次红灯报警，请及时关注调度。";
                    }else if (periodList.size() == 2){
                        reminderType = 86;
                        reminderContent = "重点工作" + rectificationInfo.getTitle() + "出现三次红灯报警，请及时关注调度。";
                    }else {
                        reminderType = 84 + periodList.size();
                        reminderContent = "重点工作" + rectificationInfo.getTitle() + "出现多次红灯报警，请及时关注调度。";
                    }
                } else if (hoursBetween <= 120) {
                    // 5天内将超期 - 黄灯（120小时 = 5天）
                    newWarnLevel = "1";
                    reminderType = 23;
                    reminderContent = "重点工作" + rectificationInfo.getTitle() + "出现黄灯提醒，请关注。";
                    log.info("节点 {} 5天内将超期，应设置为黄灯", node.getId());
                }
                // 如果预警级别发生变化，更新并发送提醒
                if (newWarnLevel != null) {
                    log.info("节点 {} 预警级别从 {} 变为 {}", node.getId(), node.getWarnLevel(), newWarnLevel);
                    node.setWarnLevel(newWarnLevel);
                    deadlineNodeMapper.updateWithNullById(node);

                    // 检查是否已经发送过相同类型的提醒
                    LambdaQueryWrapper<ReminderInfo> reminderQuery = new LambdaQueryWrapper<>();
                    reminderQuery.eq(ReminderInfo::getDeadlineId, node.getId())
                            .eq(ReminderInfo::getType, reminderType);

                    List<ReminderInfo> existingReminders = reminderInfoMapper.selectList(reminderQuery);
                    if (CollectionUtil.isEmpty(existingReminders)) {
                        log.info("节点 {} 将发送 {} 提醒", node.getId(), newWarnLevel.equals("2") ? "红灯" : "黄灯");
                        node.setTitle(rectificationInfo.getTitle());
                        redMessageWarning(node, rectificationInfo, reminderType, reminderContent);
                    } else {
                        log.info("节点 {} 已发送过 {} 提醒，不再发送", node.getId(), newWarnLevel.equals("2") ? "红灯" : "黄灯");
                    }
                } else if (newWarnLevel != null) {
                    log.info("节点 {} 预警级别未变化，仍为 {}", node.getId(), newWarnLevel);
                }
            }
        }
        log.info("预警级别更新任务执行完成");
    }

    /**
     * 检查红灯超期5天的情况
     * 每20分钟执行一次
     * 基于节点的要求完成时间计算超期天数
     */
//    @Scheduled(cron = "0 0 8 * * ?")
    private void checkRed() {
        log.info("开始检查红灯超期5天情况");
        DateTime date = DateUtil.date();

        // 查找所有红灯节点（warnLevel = "2"）且未完成的节点
        LambdaQueryWrapper<DeadlineNode> redNodeQuery = new LambdaQueryWrapper<>();
        redNodeQuery.eq(DeadlineNode::getWarnLevel, "2")
                .isNull(DeadlineNode::getEndTime); // 只处理未完成的节点

        List<DeadlineNode> redNodeList = deadlineNodeMapper.selectList(redNodeQuery);
        log.info("找到 {} 个红灯节点", redNodeList.size());

        // 过滤掉已关闭的项目和不符合条件的节点
        List<DeadlineNode> filteredRedNodeList = new ArrayList<>();
        for (DeadlineNode redNode : redNodeList) {
            // 获取对应的项目信息
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(redNode.getRectificationId());
            if (rectificationInfo == null) {
                log.info("节点 {} 对应的项目不存在，跳过", redNode.getId());
                continue;
            }

            // 过滤掉已关闭的项目
            if ("已关闭".equals(rectificationInfo.getState())) {
                log.info("节点 {} 所在项目已关闭，跳过", redNode.getId());
                continue;
            }

            // 过滤掉progress为"/"的节点
            if (redNode.getProgress() != null && redNode.getProgress().equals("/")) {
                log.info("节点 {} progress为'/'，跳过", redNode.getId());
                continue;
            }
            filteredRedNodeList.add(redNode);
        }

        log.info("过滤后剩余 {} 个红灯节点", filteredRedNodeList.size());

        for (DeadlineNode redNode : filteredRedNodeList) {
            // 获取节点的要求完成时间（考虑延期调整）
            Date deadline = redNode.getDeadlineRectificationPeriod();
            if (deadline == null) {
                deadline = redNode.getDeadline();
            }

            if (deadline == null) {
                log.info("节点 {} 没有设置期限，跳过超期5天检查", redNode.getId());
                continue;
            }

            // 计算要求完成时间到现在的小时数
            long hoursBetween = DateUtil.between(deadline, date, DateUnit.HOUR);
            log.info("节点 {} 要求完成时间: {}, 当前时间: {}, 时间差: {} 小时",
                    redNode.getId(), deadline, date, hoursBetween);

            // 如果超过120小时（5天）
            if (hoursBetween >= 120) {
                log.info("节点 {} 已超期5天，需要发送超期5天提醒", redNode.getId());

                // 检查是否已经发送过超期5天的提醒
                LambdaQueryWrapper<ReminderInfo> checkWrapper = new LambdaQueryWrapper<>();
                checkWrapper.eq(ReminderInfo::getDeadlineId, redNode.getId())
                        .eq(ReminderInfo::getType, 25);

                List<ReminderInfo> existingReminders = reminderInfoMapper.selectList(checkWrapper);

                // 如果没有发送过，发送超期5天提醒
                if (CollectionUtil.isEmpty(existingReminders)) {
                    log.info("节点 {} 未发送过超期5天提醒，准备发送", redNode.getId());
                    RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(redNode.getRectificationId());
                    if (rectificationInfo != null) {
                        redNode.setTitle(rectificationInfo.getTitle());
                        redMessageWarning(redNode, rectificationInfo, 25,
                                "您牵头的" + redNode.getTitle() + "重点工作已超期5天，请及时调度处理");
                    } else {
                        log.warn("未找到节点 {} 对应的整改信息", redNode.getRectificationId());
                    }
                } else {
                    log.info("节点 {} 已经发送过超期5天提醒，跳过", redNode.getId());
                }
            }
        }
        log.info("红灯超期5天检查完成");
    }

    /**
     * 过滤节点
     */
    private List<DeadlineNode> filiterNode(RectificationInfo rectificationInfo, List<DeadlineNode> deadlineNodeList) {
        // 排除 progress 为 / 的节点
        return deadlineNodeList.stream()
                .filter(node -> node.getProgress() == null || !"/".equals(node.getProgress()))
                .collect(Collectors.toList());
    }




    /**
     * 判断是否为牵头领导
     */
    private boolean isLeadLeader(String personName, RectificationInfo rectificationInfo) {
        if (StrUtil.isBlank(rectificationInfo.getLeadLeader())) {
            return false;
        }
        String[] leadLeaders = rectificationInfo.getLeadLeader().split("[,/.、]");
        for (String leader : leadLeaders) {
            if (leader.trim().equals(personName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否为项目责任人
     */
    private boolean isProjectResponsible(String personName, RectificationInfo rectificationInfo) {
        if (StrUtil.isBlank(rectificationInfo.getPersonLiaible())) {
            return false;
        }
        String[] responsiblePersons = rectificationInfo.getPersonLiaible().split("[,/.、]");
        for (String person : responsiblePersons) {
            if (person.trim().equals(personName)) {
                return true;
            }
        }
        return false;
    }

    private boolean isProjectLeader(String leader, RectificationInfo rectificationInfo) {
        if (StrUtil.isBlank(rectificationInfo.getPersonLiaible())) {
            return false;
        }
        String[] responsiblePersons = rectificationInfo.getLeadLeader().split("[,/.、]");
        for (String person : responsiblePersons) {
            if (person.trim().equals(leader)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否为节点责任人
     */
    private boolean isNodeResponsible(String personName, DeadlineNode deadlineNode) {
        if (StrUtil.isBlank(deadlineNode.getDescription())) {
            return false;
        }
        String[] responsiblePersons = deadlineNode.getDescription().split("[,/.、\\s]");
        for (String person : responsiblePersons) {
            if (person.trim().equals(personName)) {
                return true;
            }
        }
        return false;
    }

    //服务的企业
    // 给单位的操作人员发
    public void remindOpertioner(String departmentName,Integer type,String remindInfo,Integer reId){
        List<DsmsUser> userList = dsmsUserService.queryUserByDepartment(departmentName);
        // 不要重复发
        if (CollectionUtil.isNotEmpty(userList)) {
            DsmsUser dsmsUser = userList.get(0);
            Date today = DateUtil.beginOfDay(new Date());
            // 检查今天是否已经给该人员发送过相同项目、相同类型的提醒
            LambdaQueryWrapper<ReminderInfo> lamWrap = new LambdaQueryWrapper<ReminderInfo>()
                    .eq(ReminderInfo::getReminderPhoneNumber, dsmsUser.getMobileNo())
                    .eq(ReminderInfo::getRectificationLinkId, reId)
                    .eq(ReminderInfo::getType, type)
                    .ge(ReminderInfo::getCreatedTime, today); // 只检查今天的记录
            List<ReminderInfo> existingReminders = reminderInfoMapper.selectList(lamWrap);
            if (CollectionUtil.isEmpty(existingReminders)) {
                ReminderInfo reminderInfo = new ReminderInfo();
                reminderInfo.setReminderDepart(dsmsUser.getDepartment());
                reminderInfo.setReminderPerson(dsmsUser.getUserName());
                reminderInfo.setReminderPhoneNumber(dsmsUser.getMobileNo());
                reminderInfo.setReminderContent(remindInfo);
                reminderInfo.setReminderTime(new Date());
                reminderInfo.setRectificationLinkId(reId);
                reminderInfo.setCreatedTime(new Date());
                reminderInfo.setType(type);
                String apiResponse = null;
                try {
                    apiResponse = smsUtil.sendSmsByGet(dsmsUser.getMobileNo(), remindInfo);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                reminderInfo.setOaUser(apiResponse);
                reminderInfo.setIsSmsSent(0);
                reminderInfoMapper.insert(reminderInfo);

            }
        }

    }


    public void remindDepartment(String person,Integer type,String remindInfo,Integer reId){
        person = person.trim();
        person = person.replace(" ","");
        List<ReminderPerson> reminderPeople = reminderPersonMapper.selectList(
                new LambdaQueryWrapper<ReminderPerson>().eq(ReminderPerson::getPersonName, person));
        String targetPhone = null;
        String targetName = person;
        String department = null;
        if (CollectionUtil.isNotEmpty(reminderPeople) &&
                StringUtils.isNotBlank(reminderPeople.get(0).getPhone())) {
            targetPhone = reminderPeople.get(0).getPhone();
            targetName = reminderPeople.get(0).getPersonName();
            department = reminderPeople.get(0).getUnitName();
        }
        // 如果找不到手机号，跳过该人员
        if (StrUtil.isBlank(targetPhone)) {
            log.warn("未找到人员 {} 的手机号，跳过发送短信", person);
        }
        // 获取今天的起始时间（00:00:00）
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        // 获取今天的结束时间（23:59:59.999）
        LocalDateTime todayEnd = LocalDate.now().atTime(23, 59, 59, 999);
        // 转换为Date类型（如果需要，根据实际序列化方式调整）
        Date startDate = Date.from(todayStart.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(todayEnd.atZone(ZoneId.systemDefault()).toInstant());
        // 检查今天是否已经给该人员发送过相同项目、相同类型的提醒
        LambdaQueryWrapper<ReminderInfo> userLamWrap = new LambdaQueryWrapper<ReminderInfo>()
                .eq(ReminderInfo::getReminderPhoneNumber, targetPhone)
                .ge(ReminderInfo::getCreatedTime, startDate)  // 大于等于今天0点
                .le(ReminderInfo::getCreatedTime, endDate)   // 小于等于今天23:59:59
                .eq(ReminderInfo::getRectificationLinkId, reId);
        List<ReminderInfo> list = reminderInfoMapper.selectList(userLamWrap);
        if (list!=null && list.size()>=1){
            log.warn("已发送给，跳过发送短信", person);
            return;
        }
        ReminderInfo reminderInfo = new ReminderInfo();
        reminderInfo.setReminderDepart(department);
        reminderInfo.setReminderPerson(targetName);
        reminderInfo.setReminderPhoneNumber(targetPhone);
        reminderInfo.setReminderContent(remindInfo);
        reminderInfo.setRectificationLinkId(reId);
        reminderInfo.setReminderTime(new Date());
        reminderInfo.setCreatedTime(new Date());
        reminderInfo.setType(type);
        String apiResponse = null;
        try {
            apiResponse = smsUtil.sendSmsByGet(targetPhone, remindInfo);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        reminderInfo.setReminderPerson(targetName);
        reminderInfo.setReminderPhoneNumber(targetPhone);
        reminderInfo.setOaUser(apiResponse);
        reminderInfo.setIsSmsSent(0);
        reminderInfoMapper.insert(reminderInfo);

    }

    /**
     * 发生短信,不要重复发
     * @param phone
     * @param rectificationLinkId
     * @param reminderInfo
     */
    public void sendMsgWithOutSame(String phone,Integer rectificationLinkId,ReminderInfo reminderInfo){
        Date today = DateUtil.beginOfDay(new Date());
        // 检查今天是否已经给该人员发送过相同项目、相同类型的提醒
        LambdaQueryWrapper<ReminderInfo> lamWrap = new LambdaQueryWrapper<ReminderInfo>()
                .eq(ReminderInfo::getReminderPhoneNumber, phone)
                .eq(ReminderInfo::getRectificationLinkId, rectificationLinkId)
                .ge(ReminderInfo::getCreatedTime, today); // 只检查今天的记录
        List<ReminderInfo> existingReminders = reminderInfoMapper.selectList(lamWrap);
        if (CollectionUtil.isEmpty(existingReminders)) {
            reminderInfo.setReminderTime(new Date());
            reminderInfo.setCreatedTime(new Date());
            String apiResponse = null;
            try {
                apiResponse = smsUtil.sendSmsByGet(phone, reminderInfo.getReminderContent());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            reminderInfo.setOaUser(apiResponse);
            reminderInfo.setIsSmsSent(0);
            reminderInfoMapper.insert(reminderInfo);
        }
    }

    private void remindCityUser(Integer type,String department, RectificationInfo rectificationInfo,String remindContent){
        if (type == 24 || type>84){
            // 红灯时，要给分管副市长发送短信
            LambdaQueryWrapper<DepartmentInfo> lamWrap = new LambdaQueryWrapper<DepartmentInfo>()
                    .eq(DepartmentInfo::getDepartmentName, department);
            List<DepartmentInfo> departmentInfos = departmentInfoMapper.selectList(lamWrap);
            if (CollectionUtil.isNotEmpty(departmentInfos)){
                // 给市领导发短信;
                DepartmentInfo departInfo = departmentInfos.get(0);
                if (StrUtil.isNotBlank(departInfo.getCityPhone())){
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderDepart(department);
                    reminderInfo.setReminderPerson(departInfo.getCityName());
                    reminderInfo.setReminderPhoneNumber(departInfo.getCityPhone());
                    reminderInfo.setReminderContent(remindContent);
                    reminderInfo.setRectificationLinkId(rectificationInfo.getId());
                    reminderInfo.setReminderTime(new Date());
                    reminderInfo.setCreatedTime(new Date());
                    reminderInfo.setType(type);
                    reminderInfo.setIHgUser("分管副市长");
                    sendMsgWithOutSame(departInfo.getCityPhone(),
                            rectificationInfo.getId(),
                            reminderInfo);
                }
            }
        }else if(type == 23){
            // 分管副市长的联络员发送短信
            LambdaQueryWrapper<DepartmentInfo> lamWrap = new LambdaQueryWrapper<DepartmentInfo>()
                    .eq(DepartmentInfo::getDepartmentName, department);
            List<DepartmentInfo> departmentInfos = departmentInfoMapper.selectList(lamWrap);
            if (CollectionUtil.isNotEmpty(departmentInfos)){
                // 给市领导发短信;
                DepartmentInfo departInfo = departmentInfos.get(0);
                if (StrUtil.isNotBlank(departInfo.getSecretaryPhone())){
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderDepart(department);
                    reminderInfo.setReminderPerson(departInfo.getSecretaryName());
                    reminderInfo.setReminderPhoneNumber(departInfo.getSecretaryPhone());
                    reminderInfo.setReminderContent(remindContent);
                    reminderInfo.setRectificationLinkId(rectificationInfo.getId());
                    reminderInfo.setReminderTime(new Date());
                    reminderInfo.setCreatedTime(new Date());
                    reminderInfo.setIHgUser("分管副市长的联络员");
                    reminderInfo.setType(type);
                    sendMsgWithOutSame(departInfo.getSecretaryPhone(),
                            rectificationInfo.getId(),
                            reminderInfo);
                }
            }
        }
    }


    /**
     * 发送短信提醒
     */
    public void redMessageWarning(DeadlineNode deadlineNode, RectificationInfo rectificationInfo,
                                  Integer type, String defaultContent) {
        // 收集所有需要通知的人员
        // 推送的内容;
        // 推送的单位;
        Map<String,ReminderInfo> allResponsiblePeople = new HashMap<>();
        if (rectificationInfo.getTitle().length()>50){
            rectificationInfo.setTitle(rectificationInfo.getTitle().substring(0,50));
        }
        //责任单位主要领导（市直）
        //责任单位责任人
        //责任单位操作人员

        // 1. 环节责任人发
        if (StrUtil.isNotBlank(deadlineNode.getDescription())) {
            String[] nodeResponsiblePeople = deadlineNode.getDescription().split("[,/.、]");
            for (String person : nodeResponsiblePeople) {
                ReminderInfo reminderInfo = new ReminderInfo();
                reminderInfo.setReminderPerson(person.trim());
                reminderInfo.setReminderDepart(deadlineNode.getDepartmentName());
                //责任单位责任人 环节的
                if (type == 23){
                    String title = "重点工作"+rectificationInfo.getTitle()+"中，您负责的任务出现黄灯提醒，请及时关注。";
                    System.out.println(title);
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(23);
                }else if (type == 24){
                    String title = "重点工作"+rectificationInfo.getTitle()+"中，您负责的任务出现红灯提醒，请关注调度。";
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(24);
                }else if (type > 24){
                    String title = "";
                    if (type == 85){
                        title = "重点工作"+rectificationInfo.getTitle()+"中，您负责的任务出现二次红灯提醒，请关注调度。";
                    }else if (type == 86){
                        title = "重点工作"+rectificationInfo.getTitle()+"中，您负责的任务出现三次红灯提醒，请关注调度。";
                    }else{
                        title = "重点工作"+rectificationInfo.getTitle()+"中，您负责的任务出现多次红灯提醒，请关注调度。";
                    }
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(type);
                    reminderInfo.setIHgUser("责任单位责任人");
                }
                allResponsiblePeople.put(person.trim(),reminderInfo);
            }
        }

        // 这个项目不是市直部门的项目
        if (DISTRICTS.contains(rectificationInfo.getDepartmentName())){
            // 给操作人员发
            // 下面给项目的部门的操作人员发代替了
        }else{
            // 这里就要获取到这个人是哪个部门的
            // 责任人deadlineNode.getDescription();
            String[] realDepartments = responsiblePersonService.getDepartmentFromName(deadlineNode.getDescription());
            // 2. 定义判断逻辑：所有部门都属于县市区部门
            boolean allCountyDepartments = false;
            if (realDepartments != null && realDepartments.length > 0) {
                // 检查每一个部门是否属于县市区（部门名称包含任意县市区区域名）
                allCountyDepartments = Arrays.stream(realDepartments)
                        .allMatch(dept ->
                                // 部门不为空，且包含DISTRICTS中的任一区域名（如"黄州区"、"团风县"）
                                StrUtil.isNotBlank(dept) &&
                                        DISTRICTS.stream().anyMatch(district -> dept.contains(district))
                        );
            }
            // 3. 分支处理：所有部门都是县市区部门时执行
            if (allCountyDepartments){
                //还是县市区的
                //环节责任人所在单位不是市直单位的情况
            }else{
                // 10.13 新增功能
                // 这个就是项目是市直单位的.需要给
                // 红灯时，要给项目的分管副市长发送短信
                String remindContent = "";
                if (type == 23){
                    remindContent = "您分管单位牵头的重点工作"+rectificationInfo.getTitle()+"任务中，出现黄灯提醒，请关注。";
                }else if (type == 24){
                    remindContent = "您分管单位牵头的重点工作"+rectificationInfo.getTitle()+"任务中，出现红灯提醒，请关注。";
                }else if (type > 24) {
                if (type == 85) {
                    remindContent = "您分管单位牵头的重点工作"+rectificationInfo.getTitle()+"任务中，出现二次红灯提醒，请关注。";
                } else if (type == 86) {
                    remindContent = "您分管单位牵头的重点工作"+rectificationInfo.getTitle()+"任务中，出现三次红灯提醒，请关注。";
                } else {
                    remindContent = "您分管单位牵头的重点工作"+rectificationInfo.getTitle()+"任务中，出现多次红灯提醒，请关注。";
                }
                }
                //分管副市长,分管副市长的联络员
                remindCityUser(type,rectificationInfo.getDepartmentName(),rectificationInfo,remindContent);
                // 环节的
                // 市直责任单位的环节
                //给责任单位主要领导发
                String deptName = deadlineNode.getDepartmentName();
                if (StrUtil.isNotBlank(deptName)){
                if (deptName.contains("发改")){
                    deptName = "市发改委";
                }else if (deptName.contains("资建")){
                    deptName = "市资建局";
                }else if (deptName.contains("林业")){
                    deptName = "市林业局";
                }else if (deptName.contains("财政")){
                    deptName = "市财政局";
                }else if (deptName.contains("生态")){
                    deptName = "市生态环境局";
                }else if (deptName.contains("应急")){
                    deptName = "市应急管理局";
                }else if (deptName.contains("自规")){
                    deptName = "市自然资源规划局";
                }else if (deptName.contains("住建")){
                    deptName = "市住新局";
                }
                System.out.println(deptName);
                if (type == 23){
                    remindContent = "您分管单位负责的重点工作"+rectificationInfo.getTitle()+"任务中，出现黄灯提醒，请关注。";
                }else if (type == 24){
                    remindContent = "您分管单位负责的重点工作"+rectificationInfo.getTitle()+"任务中，出现红灯提醒，请关注。";
                }else if (type > 24) {
                    if (type == 85) {
                        remindContent = "您分管单位负责的重点工作"+rectificationInfo.getTitle()+"任务中，出现二次红灯提醒，请关注。";
                    } else if (type == 86) {
                        remindContent = "您分管单位负责的重点工作"+rectificationInfo.getTitle()+"任务中，出现三次红灯提醒，请关注。";
                    } else {
                        remindContent = "您分管单位负责的重点工作"+rectificationInfo.getTitle()+"任务中，出现多次红灯提醒，请关注。";
                    }
                }
                //分管副市长和副市长的联络员
                remindCityUser(type,deptName,rectificationInfo,remindContent);
                // 节点的市直部门的 部门分管领导
                LambdaQueryWrapper<DepartmentPerson> lamWrap = new LambdaQueryWrapper<DepartmentPerson>()
                        .eq(DepartmentPerson::getUnitName, deptName);
                List<DepartmentPerson> departmentPersonList = departmentPersonMapper.selectList(lamWrap);
                if (CollectionUtil.isNotEmpty(departmentPersonList)) {
                    for (DepartmentPerson departmentPerson : departmentPersonList) {
                        System.out.println(departmentPerson);
                        ReminderInfo reminderInfo = new ReminderInfo();
                        reminderInfo.setReminderDepart(deptName);
                        reminderInfo.setReminderPerson(departmentPerson.getPersonName());
                        if (type == 23){
                            String title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现黄灯提醒，请及时关注。";
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(23);
                        }else if (type == 24){
                            String title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现红灯提醒，请关注调度。";
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(24);
                        }else if (type > 24){
                            String title = "";
                            if (type == 85){
                                title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现二次红灯提醒，请关注调度。";
                            }else if (type == 86){
                                title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现三次红灯提醒，请关注调度。";
                            }else{
                                title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现多次红灯提醒，请关注调度。";
                            }
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(type);
                        }
                        reminderInfo.setIHgUser("责任单位主要领导");
                        reminderInfo.setReminderPhoneNumber(departmentPerson.getPhone());
                        allResponsiblePeople.put(departmentPerson.getPersonName(),reminderInfo);
                    }
                }
                // 部门的操作人员
                List<DsmsUser> userList = dsmsUserService.queryUserByDepartment(deptName);
                if (CollectionUtil.isNotEmpty(userList)) {
//                    if(.inc)
                    // 如果是县市区的

                        // 不是县市区的
//                        推送给操作人员
                        // 获取第一个操作人员名单;
                        DsmsUser dsmsUser = userList.get(0);
                        ReminderInfo reminderInfo = new ReminderInfo();
                        reminderInfo.setReminderDepart(deadlineNode.getDepartmentName());
                        reminderInfo.setReminderPerson(dsmsUser.getUserName());
                        if (type == 23){
                            String title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现黄灯提醒，请及时关注。";
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(23);
                        }else if (type == 24){
                            String title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现红灯提醒，请关注调度。";
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(24);
                        }else if (type > 24){
                            String title = "";
                            if (type == 85){
                                title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现二次红灯提醒，请关注调度。";
                            }else if (type == 86){
                                title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现三次红灯提醒，请关注调度。";
                            }else{
                                title = "重点工作"+rectificationInfo.getTitle()+"中，您单位负责的任务出现多次红灯提醒，请关注调度。";
                            }
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(type);
                        }
                        reminderInfo.setIHgUser("单位操作人员");
                        reminderInfo.setReminderPhoneNumber(dsmsUser.getMobileNo());
                        allResponsiblePeople.put(dsmsUser.getUserName(),reminderInfo);


                }
            }

            }
        }
        // 给牵头单位的责任人发

        // 2. 添加RectificationInfo的 牵头单位责任人
        if (StrUtil.isNotBlank(rectificationInfo.getPersonLiaible())) {
            String[] rectificationResponsiblePeople = rectificationInfo.getPersonLiaible().split("[,/.、]");
            for (String person : rectificationResponsiblePeople) {
                ReminderInfo reminderInfo = new ReminderInfo();
                reminderInfo.setReminderPerson(person.trim());
                reminderInfo.setReminderDepart(rectificationInfo.getDepartmentName());
                //责任单位责任人 环节的
                if (type == 23){
                    String title = "您负责的重点工作"+rectificationInfo.getTitle()+"中，出现黄灯提醒，请及时关注。";
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(23);
                }else if (type == 24){
                    String title = "您负责的重点工作"+rectificationInfo.getTitle()+"中，出现红灯提醒，请关注调度。";
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(24);
                }else if (type > 24){
                    String title = "";
                    if (type == 85){
                        title = "您负责的重点工作"+rectificationInfo.getTitle()+"中，出现二次红灯提醒，请关注调度。";
                    }else if (type == 86){
                        title = "您负责的重点工作"+rectificationInfo.getTitle()+"中，出现三次红灯提醒，请关注调度。";
                    }else{
                        title = "您负责的重点工作"+rectificationInfo.getTitle()+"中，出现多次红灯提醒，请关注调度。";
                    }
                    reminderInfo.setIHgUser("项目的责任人");
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(type);
                }
                allResponsiblePeople.put(person.trim(),reminderInfo);
            }
        }

        String leadUnit = rectificationInfo.getDepartmentName();
        String[] leadDepartment = leadUnit.split("[,/.、]");
        for (String leadDept : leadDepartment) {
            //  给牵头单位操作人员发
            List<DsmsUser> userList = dsmsUserService.queryUserByDepartment(leadDept);
            if (CollectionUtil.isNotEmpty(userList)) {
                if (DISTRICTS.contains(leadDept)) {
                    //如果是县市区的 就需要查询到对应的两办督查室和操作人员列表;
                    // 假设user类中有getJob()方法获取job字段
                    List<DsmsUser> filteredList = userList.stream()
                            .filter(user -> {
                                String job = user.getJob();
                                return "市委督查室".equals(job) || "政府督查室".equals(job) || "操作人员".equals(job);
                            }).collect(Collectors.toList());
                    if (filteredList == null || filteredList.size() == 0) {
                        filteredList = new ArrayList<>();
                        filteredList.add(userList.get(0));
                    }
                    filteredList.forEach(dsmsUser->{
                        ReminderInfo reminderInfo = new ReminderInfo();
                        reminderInfo.setReminderDepart(dsmsUser.getDepartment());
                        reminderInfo.setReminderPerson(dsmsUser.getUserName());
                        if (type == 23){
                            String title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现黄灯提醒，请及时关注。";
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(23);
                        }else if (type == 24){
                            String title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现红灯提醒，请关注调度。";
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(24);
                        }else if (type > 24){
                            String title = "";
                            if (type == 85){
                                title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现二次红灯提醒，请关注调度。";
                            }else if (type == 86){
                                title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现三次红灯提醒，请关注调度。";
                            }else{
                                title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现多次红灯提醒，请关注调度。";
                            }
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setType(type);
                        }
                        reminderInfo.setIHgUser("牵头单位操作人员");
                        reminderInfo.setReminderPhoneNumber(dsmsUser.getMobileNo());
                        allResponsiblePeople.put(dsmsUser.getUserName(),reminderInfo);
                    });
                }else{
                    DsmsUser dsmsUser = userList.get(0);
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderDepart(dsmsUser.getDepartment());
                    reminderInfo.setReminderPerson(dsmsUser.getUserName());
                    if (type == 23){
                        String title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现黄灯提醒，请及时关注。";
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setType(23);
                    }else if (type == 24){
                        String title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现红灯提醒，请关注调度。";
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setType(24);
                    }else if (type > 24){
                        String title = "";
                        if (type == 85){
                            title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现二次红灯提醒，请关注调度。";
                        }else if (type == 86){
                            title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现三次红灯提醒，请关注调度。";
                        }else{
                            title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现多次红灯提醒，请关注调度。";
                        }
                        reminderInfo.setIHgUser("牵头单位操作人员发");
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setType(type);
                    }
                    reminderInfo.setReminderPhoneNumber(dsmsUser.getMobileNo());
                    allResponsiblePeople.put(dsmsUser.getUserName(),reminderInfo);
                }

            }
            //给牵头单位的领导发
            LambdaQueryWrapper<DepartmentPerson> lamWrap = new LambdaQueryWrapper<DepartmentPerson>()
                    .eq(DepartmentPerson::getUnitName, leadDept);
            List<DepartmentPerson> departmentPersonList = departmentPersonMapper.selectList(lamWrap);
            if (CollectionUtil.isNotEmpty(departmentPersonList)) {
                for (DepartmentPerson departmentPerson : departmentPersonList) {
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderPerson(departmentPerson.getPersonName());
                    if (type == 23){
                        String title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现黄灯提醒，请及时关注。";
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setType(23);
                    }else if (type == 24){
                        String title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现红灯提醒，请关注调度。";
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setType(24);
                    }else if (type > 24){
                        String title = "";
                        if (type == 85){
                            title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现二次红灯提醒，请关注调度。";
                        }else if (type == 86){
                            title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现三次红灯提醒，请关注调度。";
                        }else{
                            title = "您单位牵头的重点工作"+rectificationInfo.getTitle()+"中，出现多次红灯提醒，请关注调度。";
                        }
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setType(type);
                    }
                    reminderInfo.setIHgUser("牵头单位的领导");
                    reminderInfo.setReminderPhoneNumber(departmentPerson.getPhone());
                    allResponsiblePeople.put(departmentPerson.getPersonName(),reminderInfo);
                }
            }
        }

        //牵头单位主要领导（市直）
        if (type == 24){
            //isProjectLeader 给项目牵头领导
            if (isProjectLeader(rectificationInfo.getLeadLeader(),rectificationInfo)){
                String[] rectificationResponsiblePeople = rectificationInfo.getLeadLeader().split("[,/.、]");
                for (String person : rectificationResponsiblePeople) {
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderPerson(person.trim());
                    String title = "您牵头的重点工作"+rectificationInfo.getTitle()+"出现红灯提醒，请及时关注调度。";
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(24);
                    reminderInfo.setIHgUser("牵头单位主要领导");
                    allResponsiblePeople.put(person,reminderInfo);
                }
            }
        }
        if (type >= 85){
            if (isProjectLeader(rectificationInfo.getLeadLeader(),rectificationInfo)){
                String[] rectificationResponsiblePeople = rectificationInfo.getLeadLeader().split("[,/.、]");
                for (String person : rectificationResponsiblePeople) {
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderPerson(person.trim());
                    String title = "您牵头的重点工作"+rectificationInfo.getTitle()+"出现二次红灯提醒，请及时关注调度。";
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(type);
                    reminderInfo.setIHgUser("牵头单位主要领导");
                    allResponsiblePeople.put(person,reminderInfo);
                }
            }
            String title = "";
            if (type == 85){
                title = "重点工作"+rectificationInfo.getTitle()+"任务中，出现二次红灯提醒，请关注。";
            }else if (type == 86){
                title = "重点工作"+rectificationInfo.getTitle()+"任务中，出现三次红灯提醒，请关注。";
            }else{
                title = "重点工作"+rectificationInfo.getTitle()+"任务中，出现多次红灯提醒，请关注。";
            }
            // 市长发
            ReminderInfo reminderInfo = new ReminderInfo();
            reminderInfo.setReminderPerson("刘洁");
            reminderInfo.setReminderContent(title);
            reminderInfo.setType(type);
            allResponsiblePeople.put("刘洁",reminderInfo);

            ReminderInfo reminderInfo2 = new ReminderInfo();
            reminderInfo2.setReminderPerson("李军杰");
            reminderInfo2.setReminderContent(title);
            reminderInfo2.setType(type);
            allResponsiblePeople.put("李军杰",reminderInfo2);

        }

        // 获取今天的日期（用于按天去重）
        Date today = DateUtil.beginOfDay(new Date());

        for(String key : allResponsiblePeople.keySet()) {
            ReminderInfo reminderInfo = allResponsiblePeople.get(key);
            String targetPhone = reminderInfo.getReminderPhoneNumber();
            String responsiblePerson = key;
            String smsContent = reminderInfo.getReminderContent();
            System.out.println(smsContent);
            if (StrUtil.isBlank(targetPhone)){
                List<ReminderPerson> reminderPeople = reminderPersonMapper.selectList(
                        new LambdaQueryWrapper<ReminderPerson>().eq(ReminderPerson::getPersonName, responsiblePerson));
                if (CollectionUtil.isNotEmpty(reminderPeople) && StringUtils.isNotBlank(reminderPeople.get(0).getPhone())) {
                    targetPhone = reminderPeople.get(0).getPhone();
                }
                // 👇 若targetPhone为null，直接跳过发送
                if (StrUtil.isBlank(targetPhone)) {
                    log.warn("未找到人员 {} 的手机号，跳过发送短信", responsiblePerson);
                    reminderInfo.setReminderPerson(responsiblePerson);
                    reminderInfo.setReminderContent(smsContent);
                    reminderInfo.setIsSmsSent(1);
                    reminderInfoMapper.insert(reminderInfo);
                    continue;
                }
            }
            reminderInfo.setReminderPerson(responsiblePerson);
            reminderInfo.setReminderPhoneNumber(targetPhone);
            reminderInfo.setDeadlineId(deadlineNode.getId());
            reminderInfo.setRectificationLinkId(deadlineNode.getRectificationId());
            reminderInfo.setCreatedTime(new Date());
            reminderInfo.setType(type);
            if (type == 23) {
                reminderInfo.setRiskLevel("1");
                reminderInfo.setReminderTitle("黄灯提醒");
            }else if (type == 24) {
                reminderInfo.setRiskLevel("2");
                reminderInfo.setReminderTitle("红灯提醒");
            }else{
                reminderInfo.setRiskLevel("2");
                reminderInfo.setReminderTitle("红灯提醒");
            }
            if (StrUtil.isEmptyIfStr(targetPhone)){
                continue;
            }
            try {
                // 检查今天是否已经给该人员发送过相同项目、相同类型的提醒
                LambdaQueryWrapper<ReminderInfo> lamWrap = new LambdaQueryWrapper<ReminderInfo>()
                        .eq(ReminderInfo::getReminderPhoneNumber, targetPhone)
                        .eq(ReminderInfo::getRectificationLinkId, deadlineNode.getRectificationId())
                        .eq(ReminderInfo::getType, type)
                        .ge(ReminderInfo::getCreatedTime, today); // 只检查今天的记录
                List<ReminderInfo> existingReminders = reminderInfoMapper.selectList(lamWrap);
                if (CollectionUtil.isEmpty(existingReminders)) {
                    // 发送短信（这里注释掉了实际的短信发送代码）
                    String apiResponse = smsUtil.sendSmsByGet(targetPhone, smsContent);
                    reminderInfo.setReminderPerson(responsiblePerson);
                    reminderInfo.setReminderPhoneNumber(targetPhone);
                    reminderInfo.setReminderContent(smsContent);
                    reminderInfo.setOaUser(apiResponse);
                    reminderInfo.setIsSmsSent(1);
                    reminderInfoMapper.insert(reminderInfo);
//                    log.info("已发送提醒给 {}：{} , {}", responsiblePerson, smsContent, apiResponse);
                } else {
                    log.info("今天已经给 {} 发送过相同项目、相同类型的提醒，跳过", responsiblePerson);
                }
            } catch (Exception e) {
                log.error("发送短信异常：{}", e.getMessage(), e);
            }
        }
    }



    /**
     * 每月1日凌晨1点自动生成当月数据（基于上月数据复制）
     * 注：需在启动类添加 @EnableScheduling 开启定时任务
     */
    @Scheduled(cron = "0 0 1 1 * ?")  // 每月1日1点执行
    public void generateNextMonthData() {
        try {
            // 1. 获取当前月第一天（作为新数据的dataMonth）
            LocalDate currentMonthFirstDay = LocalDate.now().withDayOfMonth(1);
            // 2. 获取上月第一天（作为查询条件）
            LocalDate lastMonthFirstDay = currentMonthFirstDay.minusMonths(2);
            // 3. 查询上月所有数据
            LambdaQueryWrapper<CompanyData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CompanyData::getDataMonth, lastMonthFirstDay);
            List<CompanyData> lastMonthDataList = companyDataMapper.selectList(queryWrapper);

            if (lastMonthDataList.isEmpty()) {
                // 若上月无数据，可根据业务决定是否抛出异常或跳过
                return;
            }
            lastMonthDataList.forEach(oldData -> {
                CompanyData newData = new CompanyData();
                newData.setName(oldData.getName());
                newData.setDepartmentName(oldData.getDepartmentName());
                newData.setPersonResponsible(oldData.getPersonResponsible());
                newData.setLampStatus(oldData.getLampStatus());
                newData.setBusiness(oldData.getBusiness());
                newData.setPower(oldData.getPower());
                newData.setInvoicing(oldData.getInvoicing());
                newData.setProblem(oldData.getProblem());
                newData.setRemark(oldData.getRemark());
                newData.setDataMonth(currentMonthFirstDay);
                newData.setCreatedTime(new Date());  // 新数据的创建时间为当前时间
                companyDataMapper.insert(newData);  // 需在Mapper中定义批量插入方法
            });

        } catch (Exception e) {
            e.printStackTrace();
            // 可添加日志告警或事务回滚逻辑
        }
    }

}